import Dexie from 'dexie';
import type {Table} from "dexie";

class ChatMessageDB extends Dexie {
  messageTab!: Table<msgTableItemType>;
  
  constructor(dnName:string) {
    super(dnName);
    this.version(1).stores({
      messageTab:'[timestamp+sender+session_id],[timestamp+session_id],session_id,timestamp'
    });
  }
}
let timer:number = 0;
export let chatMessageDB:ChatMessageDB ;
let timestamp = 0;

export const addMessageToDB = async (msg:msgTableItemType):Promise<boolean> => {
  if (!chatMessageDB) {
    return false;
  }
  try {
    await chatMessageDB.messageTab.put(msg);
    return true;
  } catch (e) {
    return false;
  }
}
export const updateMessageToDB = async ():Promise<boolean> => {
  if (!chatMessageDB) {
    return false;
  }
  try {
    const message: msgTableItemType = { message: "1", sender: "2", session_id: "3", status: 1, timestamp: 6 };
    let result = await chatMessageDB.messageTab.put(message);
    return true;
  } catch (e) {
    return false;
  }
}
export const getMessageBySessionID = async (session_id:string):Promise<msgTableItemType[]> => {
  if (!chatMessageDB) {
    return [];
  }
  try {
    let messageList: msgTableItemType[] = await chatMessageDB.messageTab.where('session_id').equals(session_id).toArray();
    return messageList;
  } catch (e) {
    return [];
  }
}
export const getLastMessageBySessionID = async (session_id:string):Promise<msgTableItemType|undefined> => {
  if (!chatMessageDB) {
    return undefined;
  }
  try {
    let messageList: msgTableItemType[] = await chatMessageDB.messageTab.where('session_id').equals(session_id).toArray();
    if(messageList.length === 0) {
      return undefined;
    }
    messageList.sort((a,b) => {
      return b.timestamp - a.timestamp;
    })
    return messageList[0];
  } catch (e) {
    return undefined;
  }
}
export const getMessageByTimestamp = async ():Promise<msgTableItemType[]> => {
  if (!chatMessageDB) {
    return [];
  }
  try {
    let timestamp = [0,5];
    let messageList: msgTableItemType[] = await chatMessageDB.messageTab.where('timestamp').between(timestamp[0],timestamp[1],true,true).toArray();
    return messageList;
  } catch (e) {
    return [];
  }
}
export const getMessageBySessionIDAndTimestamp = async ():Promise<msgTableItemType[]> => {
  if (!chatMessageDB) {
    return [];
  }
  try {
    let start = [0,'3'];
    let end = [5,'3'];
    let messageList: msgTableItemType[] = await chatMessageDB.messageTab.where('[timestamp+session_id]').between(start,end,true,true).toArray();
    return messageList;
  } catch (e) {
    return [];
  }
}
// 清楚超时数据（3个月）
export const clearMessageTimeout = async () => {
  const threeMonthsAgo = new Date();
  threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
  const threeMonthsAgoTimestamp = threeMonthsAgo.getTime();
  
  let deleteCount = await chatMessageDB.messageTab.where('timestamp').below(threeMonthsAgoTimestamp).delete();
  console.log(deleteCount, 'deleteCount');
  return deleteCount;
}

// 修正数据格式
export const updateTimestampType = async () => {
  if (!chatMessageDB) {
    return 0;
  }
  let updateCount = await chatMessageDB.messageTab.where('timestamp').startsWith('').modify(item => {
    item.timestamp = parseInt(String(item.timestamp));
  });
  console.log(updateCount, 'updateCount');
}


timer = setInterval(() => {
  if (!(chatMessageDB && localStorage['account'])) {
    chatMessageDB = new ChatMessageDB(`socketChatMessage-${localStorage['account']}`);
    return;
  }
  clearMessageTimeout();
  updateTimestampType();
  clearInterval(timer);
},10);
